package com.per.mybootall.controller;


import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.demo.trade.config.Configs;
import com.google.common.collect.Maps;
import com.per.mybootall.dao.ProductMapper;
import com.per.mybootall.service.AlipayInter;
import com.per.mybootall.service.OrderInter;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.security.krb5.Config;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Iterator;
import java.util.Map;

//支付宝接口：
@RestController
@RequestMapping("pay")
public class AliPayController {
    @Autowired
    private OrderInter orderInter;
@Autowired
private AlipayInter alipayInter;
@Autowired
private ProductMapper productMapper;

@PostMapping("/alipay")
    //userid,productid,usertoken,whoareuser
    public String allPay(String usertoken, String whoareuser, Long userid, Integer productid, Integer productNumber, BigDecimal producrPrice){
    System.out.println("===================================================================================");
        System.out.println("creat Order params:"+usertoken+";"+whoareuser+";"+userid+";"+producrPrice+";"+productNumber+";"+producrPrice);

        int insertResult=orderInter.creatOrder( usertoken, whoareuser, userid, productid, productNumber, producrPrice.doubleValue());
        //insertResult是插入订单返回的自增的订单id
         if(insertResult>=1){

             System.out.println("订单 creat success");

             //订单创建成功=====》》》》进入支付流程(图片---->>>>ftp)

             String productName=  productMapper.selectNameForID(productid);


             //返回的可能是网址也可能是错误信息，前端判断一下是否包含“http://”,不要搞忘了
            //注意在回调部分删除	购物车的该商品
             return alipayInter.test_trade_precreate(productName,insertResult,productNumber,producrPrice.doubleValue(),productid);

         }
        String msg="订单创建失败";
        return msg;
     }



/*支付宝会把参数全部放在request里面*/
    /*回调*/
    @PostMapping("/alipayCallBack")
    public Object alipayCallBack(HttpServletRequest request) {

        System.out.println("进入回调流程");

        Map<String,String> parames= Maps.newHashMap();

        Map requestParameter=request.getParameterMap();

        for(Iterator iter = requestParameter.keySet().iterator(); iter.hasNext(); ){
        String name=(String)iter.next();
        String[] values=(String[])requestParameter.get(name);
        String valueStr="";
        for(int i=0;i<values.length;i++){
            valueStr=(i==values.length-1)?valueStr+values[i]:valueStr+values[i]+",";
        }
        parames.put(name,valueStr);
        }

        System.out.println("支付宝回调,sign:{},trade_status:{},参数:{},"+parames.get("sign")+","+ parames.get("trade_status")+","+parames.toString());

        //验签====>>>是不是支付宝发出
        parames.remove("sign_type");

        try {
            Boolean alipayRSACheckedV2=  AlipaySignature.rsaCheckV2(parames, Configs.getAlipayPublicKey(),"utf-8",Configs.getSignType());

            //如果alipayRSACheckedV2===》true,就去减少库存，更改订单状态

        if(!alipayRSACheckedV2){
            return "非支付宝官方请求，异常请求，多次恶意请求即触发报警设备";
        }

        //就去减少库存，更改订单状态

            //out_trade_no订单号
        alipayInter.updateOrderStatus((Integer) requestParameter.get("out_trade_no"));

        //如何拿到数量?
        //        alipayInter.delProductStock(requestParameter.get("body").);
            return "success";
        } catch (AlipayApiException e) {
            System.out.println("支付宝验证回调异常"+e);
        }

        return null;
    }


/*前端对订单状态的轮询：1==>跳转支付成功      0====>继续轮询  */

}
